
const winston = require('winston');
const path = require('path');
const morgan = require('morgan');
const { createLogger, format, transports } = winston
const { combine, timestamp, label, printf, prettyPrint } = format;

const isDev = (process&&process.env&&process.env.NODE_ENV === 'production') || false

const myFormat = printf(({ level, message, label, timestamp }) => {
 return `${timestamp} [${label}] ${level}: ${message}`;
});
let logDir = !isDev?'../logs/error.log':'logs/error.log'

// 创建一个winston日志记录器
const logger = createLogger({
 level: 'http', // 只记录info之前的层级  error-0 warn-1 info-2 http-3 verbose-4 debug-5 silly-6
 // format: format.json(),
 format: combine(
  label({ label: 'right meow!' }),
  timestamp({format: 'YYYY-MM-DD HH:mm:ss'}),
  myFormat,
 ),
 defaultMeta: { service: 'user-service' },
 transports: [
   new transports.File({ 
    filename: path.resolve(__dirname,logDir), 
    maxsize: 1024*1024*10, // 10M
    maxFiles: 100, // 100个文件
    level: 'http' , // 只记录http之前的层级 error-0 warn-1 info-2 http-3 verbose-4 debug-5 silly-6
    rotationFormat: function () {
     return `${new Date().toISOString().slice(0, 13).replace(/:/g, '-')}`;
    },
    format:combine(
     label({ label: 'right meow!' }),
     timestamp({format: 'YYYY-MM-DD HH:mm:ss'}),
     myFormat,
    )
   }),
   //  日志打印到控制台
   isDev&& new transports.Console({
    format: format.simple(),
   }),
 ].filter(Boolean),
});

// 添加morgan日志信息
logger.stream = {
 write: function(message, encoding) {
   logger.error(message)
 }
}


// 错误处理中间件
function OutputError (req, res, next) {
 res.on("finish",()=>{
  // 图片访问  不记录静态资源请求  
  let type = req.url.indexOf(".png"||".jpg"||".gif"||".js"||".css"||".html")==-1
  if(res.statusCode>400&&type){
    console.log("error",path.resolve(__dirname,logDir));
    
   let err = {
    ip:req.ip,
    // url:req.url,
    url:req.originalUrl,
    body:JSON.stringify(req.body),
    method:req.method,
    params:JSON.stringify(req.params),
    statusCode:res.statusCode,
    statusMessage:res.statusMessage
   }
   let errMsg = JSON.stringify(err)
   if(res.statusCode>499) {
    logger.error(errMsg)
   }else{
    logger.info(errMsg)
   }
  }
 })
 next()
}


// * morgan 日志记录中间件记录的是全部的请求信息，成功的请求也会记录，所以需要通过 skip 方法来过滤掉不需要记录的请求。
const errorLogger = morgan('combined', {
 skip: (req, res) => res.statusCode > 400, // 可选：仅记录状态码大于 400 的请求
 immediate: false, // 允许异步写入=>接口路由发送信息后
 stream:logger.stream, 
})

module.exports = {
 logger,
 OutputLogger : OutputError,
 // OutputLogger : errorLogger
}
